<?php

declare(strict_types=1);
/**
 * This file is part of bearing-web.
 *
 * @link     https://www.bearing.cn/
 * @contact  tech@bearing.cn
 * @license  https://gitee.com/cppo/bearing_web/-/blob/master/README.md
 */

namespace frontend\controllers;

use yii\base\Event;
use yii\base\InvalidConfigException;
use yii\filters\auth\HttpBearerAuth;
use yii\helpers\ArrayHelper;
use yii\rest\ActiveController;
use yii\web\Response;

class BaseController extends ActiveController
{
    /**
     * @throws InvalidConfigException
     */
    public function init(): void
    {
        parent::init();
        Event::on(Response::class, Response::EVENT_BEFORE_SEND, [$this, 'formatDataBeforeSend']);
    }

    /**
     * 格式化接口应答.
     */
    public function formatDataBeforeSend(mixed $event): void
    {
        $response = $event->sender;
        $response->data = [
            'success' => $response->isSuccessful,
            'code' => $response->getStatusCode(),
            'message' => $response->statusText,
            'data' => $response->data,
        ];
        $response->format = Response::FORMAT_JSON;
        $response->charset = 'UTF-8';
        $response->statusCode = 200;
    }

    public function behaviors(): array
    {
        return ArrayHelper::merge(
            parent::behaviors(),
            [
                'authenticator' => [
                    'class' => HttpBearerAuth::class,
                    'optional' => ['*'],
                ],
            ]
        );
    }
}
